#pragma once

#include "CoreMinimal.h"
#include "Subsystems/GameInstanceSubsystem.h"
#include "HttpMgrSubsystem.generated.h"

UCLASS(config=Game, defaultconfig, meta=(DisplayName = "HttpManagerSetting"))
class HTTPDOWNLOADTOOL_API UHttpManagerSetting : public UDeveloperSettings
{
	GENERATED_BODY()
public:
	UHttpManagerSetting();

	UPROPERTY(config, EditAnywhere, Category = "Config | HttpManager")
	int32				MaxParallel;

	UPROPERTY(config, EditAnywhere, Category = "Config | HttpManager")
	int32				MaxTryCount;

	UPROPERTY(config, EditAnywhere, Category = "Config | HttpManager")
	int32				RequestKBSize;

	UPROPERTY(config, EditAnywhere, Category = "Config | HttpManager")
	float				ResponseTimeout;

	UPROPERTY(config, EditAnywhere, Category = "Config | HttpManager")
	FString				CurFilePath;
};

class UAsyncDownloadFile;

UCLASS()
class HTTPDOWNLOADTOOL_API UHttpMgrSubsystem : public UGameInstanceSubsystem, public FTickableGameObject
{
	GENERATED_BODY()
public:
	virtual bool ShouldCreateSubsystem(UObject* Outer) const { return true; }

	/** Implement this for initialization of instances of the system */
	virtual void Initialize(FSubsystemCollectionBase& Collection) override;

	/** Implement this for deinitialization of instances of the system */
	virtual void Deinitialize() override;

	/** Tick */
	virtual void Tick(float DeltaTime) override;
	virtual bool IsTickable() const override;
	virtual TStatId GetStatId() const override { return TStatId(); /*RETURN_QUICK_DECLARE_CYCLE_STAT(HttpMgrSubsystem, STATGROUP_Tickables);*/ }

public:
	UAsyncDownloadFile* CreateDownTask(
		UObject* WorldContextObject,
		const FString& InUrl,
		const FString& InFileName,
		const FString& InDirectory,
		bool bClearCache = false
	);

	void ExecDownloadTasks();

	void NotifyFailed(UAsyncDownloadFile* HttpFile, bool bForceFailed);
	void NotifyFinished(UAsyncDownloadFile* HttpFile);
	void ClearMgr();

private:
	void Init();

public:
	UPROPERTY()
	TArray<UAsyncDownloadFile*> DownloadHttpFiles;

	int32				MaxParallel;
	int32				MaxTryCount;
	int32				RequestKBSize;
	float				ResponseTimeout;
	FString				CurFilePath;
};
